package com.yuanqi.java.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqi.java.dto.PurchaseOrderAuditDTO;
import com.yuanqi.java.dto.PurchaseOrderDTO;
import com.yuanqi.java.entity.PurchaseOrder;
import com.yuanqi.java.result.Result;
import com.yuanqi.java.service.IPurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 采购订单主表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-08-27
 */
@RestController
@RequestMapping("/purchase-order")
public class PurchaseOrderController {
    @Autowired
    private IPurchaseOrderService purchaseOrderService;

    /**
     * 分页查询采购订单（旧：pageNum/pageSize，直接返回Map）
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> page(
            @RequestParam(defaultValue = "1") long pageNum,
            @RequestParam(defaultValue = "10") long pageSize,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) Long supplierId,
            @RequestParam(required = false) Integer status
    ) {
        Page<PurchaseOrder> page = new Page<>(pageNum, pageSize);
        QueryWrapper<PurchaseOrder> qw = new QueryWrapper<>();
        if (orderNo != null && !orderNo.trim().isEmpty()) {
            qw.like("orderNo", orderNo.trim());
        }
        if (supplierId != null) {
            qw.eq("supplier_id", supplierId);
        }
        if (status != null) {
            qw.eq("status", status);
        }
        qw.orderByDesc("create_time");
        Page<PurchaseOrder> result = purchaseOrderService.page(page, qw);
        Map<String, Object> resp = new HashMap<>();
        resp.put("records", result.getRecords());
        resp.put("total", result.getTotal());
        return ResponseEntity.ok(resp);
    }

    /**
     * 分页查询采购订单（新：current/size，返回统一Result，供前端 /purchase-order/page 使用）
     */
    @GetMapping("/page")
    public Result<Map<String, Object>> page2(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) Long supplierId,
            @RequestParam(required = false) Integer status
    ) {
        Page<PurchaseOrder> page = new Page<>(current, size);
        QueryWrapper<PurchaseOrder> qw = new QueryWrapper<>();
        if (orderNo != null && !orderNo.trim().isEmpty()) {
            qw.like("orderNo", orderNo.trim());
        }
        if (supplierId != null) {
            qw.eq("supplier_id", supplierId);
        }
        if (status != null) {
            qw.eq("status", status);
        }
        qw.orderByDesc("create_time");
        Page<PurchaseOrder> result = purchaseOrderService.page(page, qw);
        Map<String, Object> data = new HashMap<>();
        data.put("records", result.getRecords());
        data.put("total", result.getTotal());
        return Result.success(data);
    }

    /**
     * 新增采购订单
     */
    @PostMapping("/create")
    public ResponseEntity<Long> createPurchaseOrder(@Valid @RequestBody PurchaseOrderDTO purchaseOrderDTO) {
        Long orderId = purchaseOrderService.createPurchaseOrder(purchaseOrderDTO);
        return ResponseEntity.ok(orderId);
    }

    /**
     * 删除采购订单
     */
    @DeleteMapping("/{orderId}")
    public ResponseEntity<Boolean> deletePurchaseOrder(@PathVariable Long orderId) {
        boolean result = purchaseOrderService.deletePurchaseOrder(orderId);
        return ResponseEntity.ok(result);
    }

    /**
     * 提交审核
     */
    @PostMapping("/{orderId}/submit")
    public ResponseEntity<Boolean> submitForAudit(@PathVariable Long orderId) {
        boolean result = purchaseOrderService.submitForAudit(orderId);
        return ResponseEntity.ok(result);
    }

    /**
     * 审核采购订单
     */
    @PostMapping("/audit")
    public ResponseEntity<Boolean> auditPurchaseOrder(@Valid @RequestBody PurchaseOrderAuditDTO auditDTO,
                                                      @RequestHeader(value = "X-User-Id", required = false) String userIdHeader) {
        if (auditDTO.getAuditorId() == null && userIdHeader != null && !userIdHeader.isEmpty()) {
            try {
                auditDTO.setAuditorId(Long.parseLong(userIdHeader));
            } catch (NumberFormatException ignored) {}
        }
        boolean result = purchaseOrderService.auditPurchaseOrder(auditDTO);
        return ResponseEntity.ok(result);
    }

    /**
     * 获取采购订单详情（改为返回统一 Result，供退货创建弹窗加载商品明细）
     */
    @GetMapping("/{orderId}")
    public Result<PurchaseOrderDTO> getPurchaseOrderDetail(@PathVariable Long orderId) {
        PurchaseOrderDTO detail = purchaseOrderService.getPurchaseOrderDetail(orderId);
        return Result.success(detail);
    }

    /**
     * 获取所有采购订单列表（用于退货单选择）
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getAllPurchaseOrders() {
        QueryWrapper<PurchaseOrder> qw = new QueryWrapper<>();
        qw.eq("status", 2); // 只获取已审核通过的订单
        qw.orderByDesc("create_time");
        java.util.List<PurchaseOrder> orders = purchaseOrderService.list(qw);
        Map<String, Object> resp = new HashMap<>();
        resp.put("data", orders);
        return ResponseEntity.ok(resp);
    }

    /**
     * 获取采购订单商品明细（用于退货单选择）
     */
    @GetMapping("/items/{orderId}")
    public ResponseEntity<Map<String, Object>> getPurchaseOrderItems(@PathVariable Long orderId) {
        PurchaseOrderDTO detail = purchaseOrderService.getPurchaseOrderDetail(orderId);
        Map<String, Object> resp = new HashMap<>();
        resp.put("data", detail.getItems());
        return ResponseEntity.ok(resp);
    }
}
